import React, { useState } from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Checkbox, Form, Input, Flex, message } from 'antd';
import { Link, useNavigate } from 'react-router-dom';
import { login } from '../../api/auth';
import './Auth.css';

/**
 * 登录表单组件
 * @param {Object} props
 * @param {Function} props.onSuccess - 登录成功回调
 * @returns {React.ReactNode}
 */
const LoginForm = ({ onSuccess }) => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  const onFinish = async (values) => {
    try {
      setLoading(true);
      const response = await login(values);
      
      // 保存token到localStorage
      localStorage.setItem('token', response.data.token);
      
      // 保存用户角色信息到localStorage
      console.log('登录响应数据:', response.data); // 调试信息
      
      // API返回的角色信息在roles数组中
      if (response.data.roles && response.data.roles.length > 0) {
        // 取第一个角色的name作为用户角色
        const roleName = response.data.roles[0].name;
        console.log('从roles数组获取到角色:', roleName); // 调试信息
        localStorage.setItem('userRole', roleName);
      } else if (response.data.role) {
        // 兼容可能的role字段
        console.log('从role字段获取到角色:', response.data.role); // 调试信息
        localStorage.setItem('userRole', response.data.role);
      } else {
        // 如果没有找到角色信息，设置一个默认角色
        console.warn('未找到角色信息，设置默认角色: employee'); // 调试信息
        localStorage.setItem('userRole', 'employee');
      }
      
      message.success('登录成功');
      
      // 调用成功回调或跳转到首页
      if (onSuccess) {
        onSuccess(response.data);
      } else {
        navigate('/');
      }
    } catch (error) {
      console.error('登录失败:', error);
      message.error(error.response?.data?.message || '登录失败，请检查用户名和密码');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className='login-form-container'>
      <div className='login-form-header'>
        <h2>用户登录</h2>
        <p>欢迎使用人力资源管理系统</p>
      </div>
      
      <Form
        name="login"
        initialValues={{ remember: true }}
        onFinish={onFinish}
        className='login-form'
      >
        <Form.Item
          name="username"
          rules={[{ required: true, message: '请输入用户名!' }]}
        >
          <Input 
            prefix={<UserOutlined />} 
            placeholder="用户名" 
            size="large"
          />
        </Form.Item>
        
        <Form.Item
          name="password"
          rules={[{ required: true, message: '请输入密码!' }]}
        >
          <Input.Password 
            prefix={<LockOutlined />} 
            placeholder="密码" 
            size="large"
          />
        </Form.Item>
        
        <Form.Item>
          <Flex justify="space-between" align="center">
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox>记住我</Checkbox>
            </Form.Item>
            <Link to="/forgot-password">忘记密码</Link>
          </Flex>
        </Form.Item>

        <Form.Item>
          <Button 
            type="primary" 
            htmlType="submit" 
            block 
            size="large"
            loading={loading}
          >
            登录
          </Button>
        </Form.Item>
        
        <Form.Item>
          <Flex justify="center">
            <span>还没有账号？</span>
            <Link to="/register">立即注册</Link>
          </Flex>
        </Form.Item>
      </Form>
    </div>
  );
};

export default LoginForm;